<!--
 * @Description: 
 * @Author: @yangwenshan
 * @since: 2021-05-13 11:24:08
 * @LastAuthor: @yangwenshan
 * @lastTime: 2021-08-12 16:44:28
-->
<template>
  <a-drawer :title="mode == 2 ? '编辑题目类别' : '新增题目类别'" width="35%" placement="right" :visible="visible" @close="onClose">
    <a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" @submit="handleSubmit">
      <a-form-item label="类别名称">
        <a-input placeholder="请输入题目类别名称" v-decorator="[
          'name',
          {
            initialValue: data.name,
            rules: [{ required: true, message: '请输入题目类别名称' }],
          },
        ]" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 4 }">
        <a-button type="primary" html-type="submit"> 提交 </a-button>
        <a-button type="default" :style="{ marginLeft: '8px' }" @click="onClose"> 取消 </a-button>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>
<script>
import { addType, updateType } from '@/api/questionType'

export default {
  data() {
    return {
      visible: false,
      data: {},
      formLayout: 'horizontal',
      form: this.$form.createForm(this),
      mode: 0, // 0新增模式,1编辑模式
    }
  },
  watch: {
    mode(val) {
      if (val === 1) {
        this.init()
      }
    },
  },
  methods: {
    showDrawer(record, mode) {
      this.mode = mode
      if (this.mode === 2) {
        this.form.resetFields()
        this.data = record
      }
      this.visible = true
    },

    init() {
      this.form.resetFields()
      this.data = {}
    },
    onClose() {
      this.visible = false
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if(values.name && values.name.length > 50) {
            this.$notification.warning({
              message: '温馨提示',
              description: '类别名称最多50个字符'
            })
            return
          }
          const data = { ...values }
          if (this.mode === 1) {
            this.add(data)
          } else if (this.mode === 2) {
            this.edit(this.data.id, data)
          }
        }
      })
    },
    add(data) {
      addType(data).then((res) => {
        this.$message.success('新增成功')
        this.$emit('refresh')
        this.init()
        this.onClose()
      })
    },
    edit(id, data) {
      updateType(id, data).then((res) => {
        this.$message.success('修改成功')
        this.$emit('refresh')
        this.init()
        this.onClose()
      })
    },
  },
}
</script>
<style lang="less" scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
